/**
 * 
 */
package de.damontools.awolowa.application;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class WakeOnLan {

	/** 
	* @param address The broadcast IP address 
	* @param macAddress The MAC address of the computer to wake 
	* @param port 
	**/
	public static void wakeup(String macAddress) throws IOException  
	{         
		int port = 7;
    	String ip = "255.255.255.255";
	    byte[] macBytes = getBytesFromMAC(macAddress);  
	    byte[] bytes = new byte[6 + 16 * macBytes.length];  
	    for (int i = 0; i < 6; i++) {  
	        bytes[i] = (byte) 0xff;  
	    }  
	          
	    for (int i = 6; i < bytes.length; i += macBytes.length) {  
	        System.arraycopy(macBytes, 0, bytes, i, macBytes.length);  
	    }  

//	    InetAddress address = InetAddress.getByName(ipStr);
	    InetSocketAddress address = new InetSocketAddress(ip, port);

	    DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address);  
	    DatagramSocket socket = new DatagramSocket();  
	    socket.send(packet);  
	    socket.close();  
	}  
	  
	private static byte[] getBytesFromMAC(String macAddress)   
	throws IllegalArgumentException  
	{  
	    String[] hex = macAddress.split("(\\:|\\-)");  
	    if (hex.length != 6) {  
	        throw new IllegalArgumentException("Invalid MAC address.");  
	    }  
	  
	    byte[] bytes = new byte[6];   
	    try {  
	        for (int i = 0; i < 6; i++) {  
	            bytes[i] = (byte) Integer.parseInt(hex[i], 16);  
	        }  
	    }  
	    catch (NumberFormatException e) {  
	        throw new IllegalArgumentException("Invalid hex digit in MAC address: " + e.toString());  
	    }  
	      
	    return bytes;  
	} 

}